//Implementation file - Mesh.cpp

#include <vcl.h>

#include "Mesh.h"

#pragma package(smart_init)

Mesh::Mesh ( ){ nV = 0; nN = 0; nF = 0; }
Mesh::~Mesh ( ) {
        int i;
        for ( i = 0; i < nV; i++ )
                delete vertexList[i];
        for ( i = 0; i < nN; i++ )
                delete normal[i];
        for ( i = 0 ; i < nF; i++ )
                delete face[i];

        delete[] vertexList;
        delete[] normal;
        delete[] face;
}

//Accessors
int Mesh::getnV( ){ return nV; }

int Mesh::getnF( ){ return nN; }

int Mesh::getnC( ){ return nF; }

void Mesh::dibujar() {
    glPushMatrix();
      // Configurar color
      glColor3f(color.getR()/255, color.getG()/255, color.getB()/255);

      // Coger matriz actual
      GLfloat mm[16];
      glGetFloatv(GL_MODELVIEW_MATRIX,mm);
      TAfin* m = new TAfin(mm);

      // Aplicar matriz de transformacion
      m->postMultiplicar(marco);
      glLoadMatrixf(m->mat);

      dibujarMalla(false);
    glPopMatrix();
}

void Mesh::dibujarMalla(bool wire){
    for ( int i = 0 ; i < nF ; i++ ) {
        if (wire)
            glBegin( GL_LINE_LOOP );
        else
            glBegin( GL_QUADS );
        for ( int j = 0 ; j < face[i]->getnV( ) ; j++ ) {
            int iV = face[i]->getiV(j);
            int iN = face[i]->getiN(j);
            glNormal3f((GLfloat) -normal[iN]->getX(), (GLfloat) -normal[iN]->getY(), (GLfloat) -normal[iN]->getZ());
            glVertex3f((GLfloat) vertexList[iV]->getX(),
                (GLfloat) vertexList[iV]->getY(),
                (GLfloat) vertexList[iV]->getZ());
            }
        glEnd();
    }
}

VectorPoint3D* Mesh::newellMethod(VectorPoint3D** points,int s){
        float initialX = 0.0;
        float initialY = 0.0;
        float initialZ = 0.0;
        for (int i=0;i<s;i++) {
                if(i!=s-1) {
                        initialX += (points[i]->getY()-points[i+1]->getY())*(points[i]->getZ()+points[i+1]->getZ());
                        initialY += (points[i]->getZ()-points[i+1]->getZ())*(points[i]->getX()+points[i+1]->getX());
                        initialZ += (points[i]->getX()-points[i+1]->getX())*(points[i]->getY()+points[i+1]->getY());
                } else {
                        initialX += (points[i]->getY()-points[0]->getY())*(points[i]->getZ()+points[0]->getZ());
                        initialY += (points[i]->getZ()-points[0]->getZ())*(points[i]->getX()+points[0]->getX());
                        initialZ += (points[i]->getX()-points[0]->getX())*(points[i]->getY()+points[0]->getY());
                }
        }

        VectorPoint3D* finalPoint = new VectorPoint3D(initialX,initialY,initialZ);
        return finalPoint;
}



